package com.zxb;

import com.zxb.annotation.AutoWired;
import com.zxb.annotation.Controller;
import com.zxb.annotation.RequestMapping;
import com.zxb.annotation.Service;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.*;

/**
 * @author zxb
 */
public class Spring extends HttpServlet {

    private final Properties props = new Properties();

    /**
     * 存储需要实例化类的路径
     */
    private final List<String> classPath = new ArrayList<>();

    /**
     * 类容器
     */
    private final Map<String, Object> beans = new HashMap<>();

    /**
     * url映射
     */
    private final Map<String, Method> handlerMapping = new HashMap<>();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // doMapping
        try {
            doDispatcher(req, resp);
        } catch (Exception e) {
            throw new ServletException("500 server failed");
        }
    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        // 读取配置文件获取包路径
        readConfig();
        // 扫描包路径下所有有注解的类
        scanClass();
        // 反射实例化类
        initClass();
        // 依赖注入
        injectClass();
        // 初始化dispatcher-添加方法与URL映射
        doInitHandlerMapping();

        System.out.println("初始化完成！！！");

    }

    /**
     * 执行方法调用
     */
    private void doDispatcher(HttpServletRequest request, HttpServletResponse response) throws InvocationTargetException, IllegalAccessException, IOException {
        // 获取 请求 URL并替换前缀
        String requestURI = request.getRequestURI()
                .replaceAll(getServletContext().getContextPath(), "")
                .replaceAll("/+", "/");
        if (!handlerMapping.containsKey(requestURI)) {
            PrintWriter writer = response.getWriter();
            writer.write("404 Not Found！");
            writer.close();
        }
        // 获取请求参数
        Map<String, String[]> parameterMap = request.getParameterMap();

        Method method = handlerMapping.get(requestURI);
        Class<?> declaringClass = method.getDeclaringClass();
        String beanName = toFirstLowerCase(declaringClass.getSimpleName());
        method.invoke(beans.get(beanName), new Object[]{request, response, parameterMap.get("name")[0]});
    }

    /***
     * 初始化前端控制器
     */
    private void doInitHandlerMapping() {
        for (Map.Entry<String, Object> entry : beans.entrySet()) {
            Object bean = entry.getValue();
            Class<?> aClass = bean.getClass();
            // 是否包含controller注解
            if (!aClass.isAnnotationPresent(Controller.class)) {
                continue;
            }
            String baseUrl = "";
            if (aClass.isAnnotationPresent(RequestMapping.class)) {
                baseUrl = aClass.getAnnotation(RequestMapping.class).value();
            }
            Method[] methods = aClass.getMethods();
            for (Method method : methods) {
                if (method.isAnnotationPresent(RequestMapping.class)) {
                    String url = method.getAnnotation(RequestMapping.class).value();
                    baseUrl = ("/" + baseUrl + "/" + url).replaceAll("/+", "/");
                    handlerMapping.put(url, method);
                }
            }
        }
    }

    /**
     * 注入 bean
     */
    private void injectClass() {
        for (Map.Entry<String, Object> entry : beans.entrySet()) {
            Object bean = entry.getValue();
            Class<?> aClass = bean.getClass();
            // 扫描字段是否添加 autowired
            Field[] declaredFields = aClass.getDeclaredFields();
            for (Field field : declaredFields) {
                // 是否添加自动注入注解
                if (!field.isAnnotationPresent(AutoWired.class)) {
                    continue;
                }
                // 开启暴力访问
                field.setAccessible(true);

                AutoWired autoWiredAnnotation = field.getAnnotation(AutoWired.class);
                String beanName = autoWiredAnnotation.value().trim();
                if ("".equals(beanName)) {
                    beanName = field.getType().getName();
                }
                // 注入
                try {
                    field.set(entry.getValue(), beans.get(beanName));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 初始化类实例
     */
    private void initClass() {
        classPath.forEach(className -> {
            Class<?> clazz = null;
            try {
                clazz = Class.forName(className);
                // 有 controller 注解
                if (clazz.isAnnotationPresent(Controller.class)) {
                    beans.put(toFirstLowerCase(clazz.getSimpleName()), clazz.newInstance());
                } else if (clazz.isAnnotationPresent(Service.class)) {
                    // 有 service 注解
                    Service annotation = clazz.getAnnotation(Service.class);
                    String value = annotation.value();
                    String simpleName = toFirstLowerCase(clazz.getSimpleName());
                    if (!"".equals(value)) {
                        simpleName = value;
                    }
                    Object o = clazz.newInstance();
                    beans.put(simpleName, o);
                    Class<?>[] interfaces = clazz.getInterfaces();
                    // 实例化所有接口
                    for (Class<?> i : interfaces) {
                        String name = i.getName();
                        // 如果接口有多个实例则抛异常
                        if (beans.containsKey(name)) {
                            throw new IllegalArgumentException("bean is exists!");
                        }
                        beans.put(name, o);
                    }
                }
            } catch (ClassNotFoundException | IllegalAccessException | InstantiationException e) {
                e.printStackTrace();
            }
        });
    }

    /**
     * 首字母小写
     *
     * @param source
     * @return
     */
    private String toFirstLowerCase(String source) {
        char[] chars = source.toCharArray();
        chars[0] = (char) (chars[0] + 32);
        return String.valueOf(chars);
    }

    /**
     * 扫描包路径下的所有添加注解的类名
     */
    private void scanClass() {
        // 获取包路径
        String basePackage = props.getProperty("basePackage");
        URL resource = Thread.currentThread().getContextClassLoader().getResource(basePackage.replace(".", "/"));
        if (resource == null) {
            throw new RuntimeException("500 classpath not found!");
        }
        String filePath = resource.getPath();
        classPath.addAll(addAllClasses(filePath));
    }

    /**
     * 遍历文件夹，扫描所有子类
     *
     * @param filePath
     * @return
     */
    private List<String> addAllClasses(String filePath) {
        List<String> list = new ArrayList<>();
        File file = new File(filePath);
        File[] childFiles = file.listFiles();
        for (File childFile : Objects.requireNonNull(childFiles)) {
            if (childFile.isDirectory()) {
                list.addAll(addAllClasses(childFile.getPath()));
            } else {
                String childFilePath = childFile.getPath();
                if (childFilePath.endsWith(".class")) {
                    childFilePath = childFilePath.substring(childFilePath.indexOf("\\classes") + 9,
                            childFilePath.lastIndexOf("."));
                    childFilePath = childFilePath.replace("\\", ".");
                    list.add(childFilePath);
                }
            }
        }
        return list;
    }

    /**
     * 读取classpath下知指定文件
     */
    private void readConfig() {
        String path = this.getServletContext().getInitParameter("contextConfigLocation");
        try (InputStream is = this.getServletContext().getResourceAsStream(path)) {

            props.load(is);

        } catch (IOException e) {
            System.out.println("读取异常！" + e.getMessage());
        }

    }
}
